/*
1. eventloop就是事件循环，消息队列是一个队列，在浏览器环境下主要用于存放异步任务，也就是宏任务。微任务是优先级高于宏任务的
任务，本质上是在把任务放在当前调用栈的底部，在上面的任务执行完之后会立刻执行，调用栈清空之后，事件循环会把消息队列里面的
任务按先后循序压入调用栈执行。
常见的微任务：mutationObserver，Promise和nextTick
常见的宏任务：setTimeout，setInterval，ajax（浏览器）
*/
class MayBe {
  static of(value) {
    return new MayBe(value)
  }
  constructor(value) {
    this._value = value
  }
  map(fn) {
    // 处理方法是返回一个值为null的函子
    return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this._value))
  }
  isNothing() {
    return this._value === null || this._value === undefined
  }
}

/*2. promie改写setTimeout */
const promise = new Promise((resolve) => {
  setTimeout(resolve, 10)
})
promise
  .then(() => {
    var a = 'hello'
    return a
  })
  .then((value) => {
    var b = 'lagou'
    return value + ' ' + b
  })
  .then((value) => {
    var c = 'I like you'
    return value + ' ' + c
  })
  .then((value) => {
    console.log(value)
  })

/* 3. fp编程练习 */
const fp = require('lodash/fp')
const last_car = (cars) => fp.last(cars)
const isLastInStock = (last_car) => fp.prop('in-stock', last_car)
const f1 = fp.flowRight(isLastInStock, last_car)

/* 4. 获取第一个car的name */
const first_car = (cars) => fp.first(cars)
const getName = (first_car) => fp.prop('name', first_car)
const f2 = fp.flowRight(getName, first_car)

/* 5. AverageDollarValue */
let _average = function (xs) {
  return fp.reduce(fp.add, 0, xs) / xs.length
}

const dollar_values = fp.map(function (car) {
  return car.dollar_values
}, cars)
const f3 = fp.flowRight(_average, dollar_values)
console.log(f3(cars))

/* 6. sanitizeNames \W 匹配非word字符*/
let _underscore = fp.replace(/\W+/g, '_')
const sanitizeNames = fp.flowRight(_underscore, fp.toLower)
console.log(f('Hello World'))

/* 7. 函子 */
// const { Maybe, Container } = require('./support')
let mayBe = MayBe.of([5, 6, 1])
let ex1 = () => {
  return fp.map((x) => fp.add(x, 1), mayBe._value)
}
console.log(ex1())
let ex2 = () => {
  return fp.first(mayBe._value)
}
console.log(ex2())

let safeProp = fp.curry(function (x, o) {
  return MayBe.of(o[x])
})
let user = { id: 2, name: 'Albert' }
let ex3 = () => {
  // 找到user首字母
  return fp.first(safeProp('name', user)._value)
}
console.log(ex3())

// let ex4 = function (n) {
//   if (n) {
//     return parseInt(n)
//   }
// }
let ex4 = (x) => parseInt(MayBe.of(x)._value)
// .map((x) => parseInt(x))
console.log(ex4(null))

/* 8. 手写Promise */
// 添加并行的操作！
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  // 添加对执行器的错误的捕获
  // 也就是new的时候的错误
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }
  // promise状态
  status = PENDING
  value = undefined
  reason = undefined
  // 用箭头函数以便于this指向实例对象
  // 成功回调
  successCB = []
  // 失败回调
  failCB = []
  resolve = (value) => {
    // 如果状态不是pending组织程序向下执行：实现只有等待的情况下状态可以更改
    if (this.status !== PENDING) return
    // 将状态更改为成功
    this.status = FULFILLED
    // 保存成功之后的值
    this.value = value
    // 处理异步的情况，如果成功的回调存在就调用
    // this.successCB && this.successCB(this.value);
    while (this.successCB.length) {
      // shift返回第一个添加进数组的回调函数
      // this.successCB.shift()(this.value);
      // 不需要传值了，调用的时候已经传完值了
      this.successCB.shift()()
    }
  }

  // 保存失败之后的原因
  reject = (reason) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    // 保存失败之后的原因
    this.reason = reason
    // 处理异步的情况，如果失败的回调存在就调用
    // this.failCB && this.failCB(this.reason);
    while (this.failCB.length) {
      // shift返回第一个添加进数组的回调函数，并从原数组中删除这个函数
      // this.failCB.shift()(this.reason);
      // 不需要传值了，调用的时候已经传完值了
      this.failCB.shift()()
    }
  }

  then(successCB, failCB) {
    successCB = successCB ? successCB : (value) => value
    failCB = failCB
      ? failCB
      : (reason) => {
          throw reason
        }
    // 返回promise
    let promise2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            // 通过resolve传递值
            /* 
            普通值，直接resolve
            promise对象，查看返回结果，根据返回结果决定调用resolve还是reject
            获取自己需要异步，同步的话是不能获取的！
            */
            let x = successCB(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
        // resolve(x);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            // 通过reject传递失败的消息
            /* 
            promise对象，查看返回结果，根据返回结果决定调用resolve还是reject
            获取自己需要异步，同步的话是不能获取的！
            */
            let x = failCB(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        // 等待
        this.successCB.push(() => {
          setTimeout(() => {
            try {
              // 通过resolve传递值
              /* 
              普通值，直接resolve
              promise对象，查看返回结果，根据返回结果决定调用resolve还是reject
              获取自己需要异步，同步的话是不能获取的！
              */
              let x = successCB(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
        this.failCB.push(() => {
          setTimeout(() => {
            try {
              // 通过resolve传递值
              /* 
              普通值，直接resolve
              promise对象，查看返回结果，根据返回结果决定调用resolve还是reject
              获取自己需要异步，同步的话是不能获取的！
              */
              let x = failCB(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    })
    return promise2
  }
  finally(callback) {
    return this.then(
      (value) => {
        // callback();
        // return value;
        return MyPromise.resolve(callback()).then(() => value)
      },
      (reason) => {
        // callback();
        // throw reason;
        return MyPromise.resolve(callback()).then(() => throw reason)
      }
    )
  }
  static resolve(val) {
    if (val instanceof MyPromise) return val
    return new MyPromise((resolve) => resolve(val))
  }
  static all(arr) {
    let res = []
    let index = 0
    return new MyPromise((resolve, reject) => {
      // index === arr.length是等待异步结果的！
      function addData(key, val) {
        res[key] = value
        index++
        if (index === arr.length) {
          resolve(res)
        }
      }
      for (let i = 0; i < arr.length; i++) {
        let cur = arr[i]
        if (cur instanceof MyPromise) {
          // Promise对象
          cur.then(
            (value) => addData(i, value),
            (reason) => reject(reason)
          )
        } else {
          addData(i, array[i])
        }
      }
    })
  }
  static catch(failCB) {
    return this.then(undefined, failCB)
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof MyPromise) {
    x.then(
      // (value) => resolve(value),
      // (reason) => reject(value)
      // 简化写法
      resolve,
      reject
    )
  } else {
    resolve(x)
  }
}
module.exports = MyPromise
